package client

import (
	"encoding/hex"
	"gitee.com/yangzx6606/core/pattern"
)

type PacketType int

const (
	PacketTypeConnected   PacketType = 0 // 连接成功
	PacketTypeConnectLost PacketType = 1 // 连接断开
	PacketTypeData        PacketType = 2 // 数据包
)

func (p PacketType) ToString() string {
	switch p {
	case PacketTypeConnected:
		return "连接成功"
	case PacketTypeConnectLost:
		return "连接断开"
	case PacketTypeData:
		return ""
	}
	return "未知"
}

// Packet 连接状态也通过该数据包回调
type Packet struct {
	Type PacketType
	Data []byte
}

func (p *Packet) ToString() string {
	if p.Type == PacketTypeData {
		return hex.EncodeToString(p.Data)
	}
	return p.Type.ToString()
}

func NewPacket(t PacketType, data []byte) *Packet {
	p := &Packet{Type: t}

	if data != nil {
		p.Data = make([]byte, len(data))
		copy(p.Data, data)
	}
	return p
}

type Client interface {
	pattern.Subject[*Packet]
	Open() error
	Write(*Packet) error
	Close()
}
